package com.example.readandwriteseparation.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 动态数据源提供者
 *
 * @author csp 2021-08-23
 */
@Configuration
@ConfigurationProperties(prefix = "spring")
public class DataSourceProvider{

    private Map<String, DataSourceProperties> dataSourceMap;

    private DataSource buildDataSource(DataSourceProperties prop) {
        DruidDataSource builder = DruidDataSourceBuilder.create().build();
        builder.setDriverClassName(prop.getDriverClassName());
        builder.setUsername(prop.getUsername());
        builder.setPassword(prop.getPassword());
        builder.setUrl(prop.getUrl());
        return builder;
    }

    public DataSource provide(String key) {
        DataSourceProperties properties = dataSourceMap.get(key);
        if (properties == null) {
            return null;
        }
      return buildDataSource(properties);
    }

    public void setDataSource(Map<String, DataSourceProperties> dataSource) {
        this.dataSourceMap = dataSource;
    }



}
